import sys

def nearNum(target,list0):
    min_delta = sys.maxsize
    for i in list0:
        if target <  i:
            min_delta = min(min_delta,i-target)
    if min_delta == sys.maxsize:
        return sys.maxsize
    else:
        return target + min_delta      

def printAll(l0,flag):
    if flag < 0:
        return 
    print(l0)
    index0 = len(l0) - 1
    index = index0
    while l0[index] < l0[index-1]:
        index -= 1
    if (index-1) < 0:
        return
    key_num = l0[index-1]
    l2 = l0[index:index0+1]
    near_num = nearNum(key_num,l2)
    if (near_num) in l0:
        near_index = l0.index(near_num)
    else:
        return
    l0[index-1], l0[near_index] = l0[near_index], l0[index-1]
    l2 = l0[index:index0+1]
    # print('l2 before sort',l2)
    l2.sort(reverse=False)
    # print('l2 after sort',l2)
    l0[index:index0+1] = l2
    printAll(l0,index-1)

    

if __name__ == "__main__":
    list0 = list(range(1,5))
    digit_len = 3
    num_len = len(list0)
    for i in list0:
        list1 = list(range(1,5))
        list1.pop(list1.index(i))
        # list1.insert(0,i)
        # print('###'+str(i)+str(list1))
        printAll(list1,num_len-1)
        